//Given a string s consists of some words separated by spaces, return the length
// of the last word in the string. If the last word does not exist, return 0. 
//
// A word is a maximal substring consisting of non-space characters only. 
//
// 
// Example 1: 
// Input: s = "Hello World"
//Output: 5
// Example 2: 
// Input: s = " "
//Output: 0
// 
// 
// Constraints: 
//
// 
// 1 <= s.length <= 104 
// s consists of only English letters and spaces ' '. 
// 
// Related Topics 字符串 
// 👍 311 👎 0


package leetcode.editor.cn;

//Java：Length of Last Word
class P58LengthOfLastWord {
    public static void main(String[] args) {
        Solution solution = new P58LengthOfLastWord().new Solution();
        // TO TEST
        System.out.println(solution.lengthOfLastWord("hello a"));
    }

    //leetcode submit region begin(Prohibit modification and deletion)
    class Solution {
        public int lengthOfLastWordApi(String s) {
            String[] arr = s.split(" ");
            if (arr.length == 0) {
                return 0;
            }

            return arr[arr.length - 1].length();
        }

        public int lengthOfLastWord(String s) {
            int begin = 0;
            int i = s.length() - 1;
            int end = s.length();
            boolean match = true;
            for (; i >= 0; i--) {
                if (s.charAt(i) == ' ') {
                    if (match) {
                        end--;
                    } else {
                        begin = i + 1;
                        break;
                    }
                } else {
                    match = false;
                }
            }
            return end - begin;
        }
    }
//leetcode submit region end(Prohibit modification and deletion)

}